define(['app', 'js/filter/filterProduct', 'datetime', 'autocomplete', 'pagination', 'editor'], function(app) {
    'use strict';
    app.controller('Product', function($scope, dataFactoryCRM, $q, $rootScope, $routeParams, crmParam, $timeout) {
        $scope.productPage = { pageAll: 1, pageNow: 1, pageSize: $scope.psize, k: 3 };    //分页参数
        $scope.search_param = { product_name: ''};   //页面搜索参数
        $scope.product_list;
        $scope.product_line = [{}];
        $scope.product_lineall = [{}];
        $scope.teacherList = [{}];      //投资顾问
        $scope.productLineCode_check;
        $scope.search_product_line = "";
        $scope.add_name = '';
        $scope.aaa = "";
        $scope.dataRiskRank = crmParam.get( 'productRiskRank');//产品风险等级参数
        $scope.add_risk_rank = 0;

         $scope.$watch('$viewContentLoading',function(event, viewConfig){ 
            $scope.aaa = "";
        });

        /**获取产品线数据**/
        $scope.getProductLineDate = function(){
            dataFactoryCRM.getDataByAPI('Product/getProductLine').then(function(returnDate) {
                if(returnDate.rcode){
                    $scope.product_line = returnDate.data;
                    var j = 1;
                    for (var i = 0; i < $scope.product_line.length; i++) {
                        $scope.product_lineall[j] = $scope.product_line[i];
                        j++;
                    };
                    //添加“所有产品线”选项
                    $scope.product_lineall[0] = {'name':'所有产品线','product_line_code':-1};
                }else{
                    $scope.product_line = [{}];
                    $scope.product_lineall = [{}];
                }
                if($routeParams.product_line_code && $scope.aaa ==""){
                    $scope.search_param.product_line = $routeParams.product_line_code;  //获取url传值
                }else{
                    $scope.search_param.product_line = '-1';
                }
                $scope.getProductList($scope.search_param.product_line);
            });
        }

        /**获取列表页 */
        $scope.getProductList = function() {
            var listParam = $scope.search_param;
            listParam['psize'] = $scope.productPage.pageSize;
            listParam['p'] = $scope.productPage.pageNow;
            var search_url = 'Product/index?' + $.param(listParam);
            dataFactoryCRM.getDataByAPI(search_url).then(function(returnDate) {
                $scope.rcode = returnDate.rcode;
                $scope.productPage.pageSize = returnDate.psize;
                $scope.productPage.pageAll = returnDate.pall;
                $scope.productPage.pageNow = returnDate.p;
                $scope.product_list = returnDate.data;
            });
        };

        /**搜索事件**/
        $scope.search = function() {
            $scope.getProductList();
        }

        //特殊处理semantic dropdown的反向绑定缺陷
        $scope.$watch('search_param.product_line', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='search_param.product_line']").dropdown('set selected', newValue);
            });
        }, true);

        /*产品跳转到套餐*/
        $scope.viewPackage = function(product_id){
            $rootScope.go('/product_package/'+product_id);
        }

        /*投资顾问监听输入内容*/
        $scope.teacherInputChanged = function($item) {
            $scope.detectTeacher = $item;
        }
        /*添加-监听输入付款人信息*/
        $scope.$watch('detectTeacher', function(newvalue, oldvalue) {
            if (newvalue != oldvalue) {
                dataFactoryCRM.postDataByAPI('Product/getTeacherInfo', 'nickname=' + $scope.detectTeacher)
                    .then(function(d) {
                        if (d.rcode) {
                            $scope.teacherList = d.data;
                        } else {
                            $scope.teacherList = [{}];
                        }
                    });
            }
        });
        /**添加-投资顾问自动补全**/
        $scope.selecteTeacher = function(selected){
            if (selected){
                $("#add_teacher").val(selected.description.user_id);
            }else{
                $("#add_teacher").val('');
            }
            $('#add_teacher').trigger('change');
        }

        /*添加-监听产品名*/
        $scope.$watch('add_name', function(newvalue, oldvalue) {
            var product_line_code = $("#product_line_code").val();
            if (newvalue != oldvalue) {
                $scope.checkNameExist(product_line_code);
            } 
        });
        /*添加-判断同一产品线下，产品名是否重名*/
        $scope.checkNameExist = function(product_line_code){
            dataFactoryCRM.postDataByAPI('Product/checkNameExist','product_line_code='+product_line_code+'&name=' +$scope.add_name)
                .then(function(d) {
                    if (d.rcode) { //已存在，不能添加
                        $("#checkExist").val('exist');
                        return false;
                    } else {
                        $("#checkExist").val('noexist');
                    }
                });
        }

        /*成功弹窗弹出事件*/
        $scope.successFun = function(){
            $('.ui.modal.OK').modal('show');
            setTimeout(function() {
                $('.ui.modal.OK').modal('hide')
            }, 3000)
        }
        /*失败弹窗弹出事件*/
        $scope.failFun = function(){
            $(".ui.modal.Fail").modal('show');
            setTimeout(function() {
                $('.ui.modal.Fail').modal('hide')
            }, 3000);
        }

        /**添加产品界面**/
        $scope.showAddProduct = function(){
            $scope.addData = {name:'',manager_id:'',remark:''};
            $(".frm.add").form('reset');
            $scope.$broadcast('angucomplete-alt:clearInput');
            $('.add_product.modal').modal({
                observeChanges: true,
                onApprove: function() {
                    if ($('.frm.add').form('is valid')) {
                        $scope.addProduct( $scope.addData);
                    } else   
                    return false;
                }
            }).modal('show');
        }

        /**添加产品功能**/
        $scope.addProduct = function( _data ){
            dataFactoryCRM.postDataByAPI('Product/addProduct', _data)
                .then(function(data) {
                    if (data.rcode) {
                        $scope.msg = '添加产品成功';
                        $scope.successFun();
                        $scope.getProductList();
                        return true;
                    } else {
                        $scope.msg = data.msg;
                        $scope.failFun();
                        return false;
                    }
                });
        }

        /**编辑-投资顾问自动补全**/
        $scope.selecteTeacherEdit = function(selected){
            if(selected){
                $("#update_teacher").val(selected.description.user_id);
            }else{
                $("#update_teacher").val($("#update_manager_id").val());
            }
            $('#update_teacher').trigger('change');
        }

        /*编辑-监听产品名*/
        $scope.$watch('edit_name', function(newvalue, oldvalue) {
            if (newvalue != oldvalue ) {
                $scope.checkNameExistEdit($scope.edit_line_code);
            }
        });
        /*编辑-判断同一产品线下，产品名是否重名*/
        $scope.checkNameExistEdit = function(product_line_codeEdit){
            var checkUrl = 'product_line_code='+product_line_codeEdit+'&name=' +$scope.edit_name+'&product_id='+$("#update_product_id").val();
            dataFactoryCRM.postDataByAPI('Product/checkNameExist',checkUrl)
                .then(function(d) {
                    if (d.rcode) { //已存在，不能添加
                        $("#checkExistEdit").val('exist');
                        return false;
                    } else {
                        $("#checkExistEdit").val('noexist');
                    }
                });
        }

        /*编辑产品界面*/
        $scope.showEditProduct = function( product_id ){
            $scope.editData = {product_id:product_id,manager_name:''};
            function _updateProduct( _pdata ) {
                dataFactoryCRM.postDataByAPI('product/editProduct', _pdata )
                    .then(function(d){
                        $scope.userMsg = d.msg;
                        if (d.rcode){
                            $scope.msg = '编辑产品成功';
                            $scope.successFun();
                            $scope.getProductList();
                            return true;
                        } else{
                            $scope.msg = data.msg;
                            $scope.failFun();
                            return false;
                        }
                    });
            }
            $timeout(function(){
                 $scope.$broadcast('angucomplete-alt:clearInput');
                 $(".frm.edit").form('reset');
            });
            
            dataFactoryCRM.getDataByAPI('product/editProduct?product_id='+product_id )
                .then(function(d){
                    if (d&&d.rcode) {
                            $timeout(function(){
                                $scope.editData = d.data;
                                $('.edit_risk').dropdown('set selected', $scope.editData.risk_rank);
                                 $("#update_teachername_value").val($scope.editData.manager_name);
                            });
                        $('.ui.edit.modal').modal({
                            onApprove:function(){
                                if ($('.frm.edit').form('is valid')) {
                                    _updateProduct( $scope.editData );
                                } else {
                                    return false;
                                }
                            }
                        }) .modal('show');
                    } else{
                        $scope.msg = d.msg;
                        $scope.failFun();
                    }
                },
                function(){
                    $scope.msg = '接口请求失败';
                    $scope.failFun();
                }
            );
        }
        
        /*删除产品*/
        $scope.delProduct = function(){
            var _product = this.vproduct;
            $('.del.modal').modal({
                onApprove: function() {
                    dataFactoryCRM.getDataByAPI('product/delProduct?id=' + _product.product_id)
                        .then(function(data) {
                            if (data.rcode == 1) {
                                $scope.msg = '产品删除成功';
                                $scope.successFun();
                                if ($scope.product_list) {
                                    var i = 0;
                                    for (; i < $scope.product_list.length; i++) {
                                        if ($scope.product_list[i].product_id == _product.product_id) {
                                            $scope.product_list.splice(i, 1);
                                            break;
                                        }
                                    }
                                }
                            } else {
                                $scope.msg = data.msg;
                                $scope.failFun();
                                return false;
                            }
                        });
                    return true;
                }
            }).modal('show');
        }

        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function(){
            $scope.getProductLineDate();   //判断url中产品所属产品线
        });

    })
    .directive('productRiskRank', function( crmParam ) {
            var _pRiskRank =  crmParam.get( 'productRiskRank');
            var pRiskRank = {};
            _pRiskRank.forEach(function(v){
                pRiskRank[v.sys_param_detail_id] = v.detail_name;
            });
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.rank&& attrs.rank in pRiskRank)
                        scope.status = pRiskRank[attrs.rank];
                }
            };
        });

})